package com.xzq.bugstack.client;

import com.xzq.bugstack.domain.Constants;
import com.xzq.bugstack.domain.FileBurstData;
import com.xzq.bugstack.domain.FileBurstInstruct;
import com.xzq.bugstack.domain.FileTransferProtocol;
import com.xzq.bugstack.util.FileUtil;
import com.xzq.bugstack.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 18:31
 * @Version 1.0.0
 **/
public class MyClientHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof FileTransferProtocol)) {
            return;
        }
        FileTransferProtocol fileTransferProtocol = (FileTransferProtocol) msg;
        Integer transferType = fileTransferProtocol.getTransferType();
        switch (transferType) {
            case 1:
                FileBurstInstruct fileBurstInstruct = (FileBurstInstruct) fileTransferProtocol.getTranferObj();
                //Constants.FileStatus(0开始 1 中间 2结尾  3完成)
                if (Constants.FileStatus.COMPLETE == fileBurstInstruct.getStatus()) {
                    ctx.flush();
                    ctx.close();
                    System.out.println(-1);
                    return;
                }
                FileBurstData fileBurstData = FileUtil.readFile(fileBurstInstruct.getClientFileUrl(), fileBurstInstruct.getReadPosition());
                ctx.writeAndFlush(MsgUtil.buildTransferData(fileBurstData));
                System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ " xzq客户端传输文件信息。FILE：" + fileBurstData.getFileName() + " SIZE(byte)：" + (fileBurstData.getEndPos() - fileBurstData.getBeginPos()));
                break;
            default:
                break;
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel sc = (SocketChannel) ctx.channel();
        System.out.println("建立连接....");
        System.out.println("服务端IP:" + sc.localAddress().getHostString());
        System.out.println("服务端端口:" + sc.localAddress().getPort());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接断开：" + ctx.channel().localAddress().toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("连接异常：\r\n" + cause.getMessage());
    }
}
